package net.sureon.web.admin;

import net.sureon.app.AppContext;
import net.sureon.biz.UserBO;
import net.sureon.biz.UserMgr;
import net.sureon.common.SureonConstants;
import net.sureon.common.exception.SureonException;
import net.sureon.common.security.Role;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

public class ManageUserValidator implements Validator {

	private UserMgr userMgr;

	/**
	 * @return the userMgr
	 */
	public UserMgr getUserMgr() {
		return userMgr;
	}

	/**
	 * @param userMgr
	 *            the userMgr to set
	 */
	public void setUserMgr(UserMgr userMgr) {
		this.userMgr = userMgr;
	}

	public boolean supports(Class clazz) {
		// TODO Auto-generated method stub
		return true;
	}

	public void validate(Object target, Errors errors) {
		UserForm userForm = (UserForm) target;
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "email不能为空");
		String email = userForm.getEmail();
		if (email == null || "".equals(email.trim())) {
			errors.rejectValue("email", "email不能为空");
		} else {
			if(!SureonConstants.EMAIL_PATTERN.matcher(email).matches()){
				errors.rejectValue("email", "email格式不正确");				
			}
		}
		
		String userName = email;
		if (userName == null || "".equals(userName.trim())) {
			errors.rejectValue("userName", "请填写用户名");
		} else {
			try {
				UserBO testUser = userMgr.getUserByUsername(AppContext
						.getCompanyID(), userName);
				if (userForm.getUserID() <= 0
						|| testUser.getUserID() != userForm.getUserID()) {
					errors.rejectValue("userName", "用户名不能重复，请用其他用户名");
				}
			} catch (SureonException e2) {
				// ignore
			}
		}
		if (userForm.getRole() == null
				|| Role.getRole(userForm.getRole()) == null) {
			errors.rejectValue("role", "请选择相应权限");
		}
		if (userForm.getGroupID() <= 0) {
			errors.rejectValue("groupID", "请选择团队");
		}

	}

}
